package com.jackrain.nea.ad.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.ad.api.AdParamDelCmd;
import com.jackrain.nea.ad.mapper.AdParamMapper;
import com.jackrain.nea.common.ValueHolderUtils;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.utils.AdParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 系统参数
 * @author Yvan
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "ad")
public class AdParamDelCmdImpl extends CommandAdapter implements AdParamDelCmd {
    
    @Override
    public ValueHolder execute(QuerySession session) throws NDSException {
        DefaultWebEvent event = session.getEvent();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(
                event.getParameterValue("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue),
                Feature.OrderedField);

        if(param != null){
            Long id = param.getLong("objid");
            if(id != null){
                AdParamMapper mapper = ApplicationContextHandle.getBean(AdParamMapper.class);
                HashMap<String, Object> sqlData = mapper.getById(id);
                if(sqlData != null){
                    int res = mapper.delete(id);
                    if(res > 0){
                        if("ProductAutoSynCol".equals(sqlData.get("NAME"))){
                            AdParamUtil.delParam("ProductAutoSynCol");
                        }
                        return ValueHolderUtils.success();
                    }
                }
            }
        }
        throw new NDSException("当前记录已不存在！");
    }
}
